import React from 'react';
import { Select, Button, Input } from 'antd';
import FormItem from '../../../../../components/FormItem';

export const isJson = (value) => {
  try {
    return typeof JSON.parse(value) === 'object';
  } catch (error) {
    return false;
  }
};

const josnExample = JSON.stringify(JSON.parse('{"key1":"value1","key2":"value2"}'), null, 4)

const ReturnResult = (props) => {
  const { form, value } = props;
  const { getFieldValue, setFieldsValue } = form;

  // 格式化
  const handleFormatter = (type) => {
    const tempType = type ? 'failedExample' : 'successExample';
    const value = getFieldValue(tempType);
    props.form.validateFields([tempType], (err, values) => {
      if (!err) {
        // eslint-disable-next-line no-eval
        const tempValue = isJson(value) ? JSON.stringify(eval(`(${value})`), null, 4) : value;
        setFieldsValue({ [tempType]: tempValue });
      }
    });
  };

  const validateReturnValue = (_, value, type) => {
    if (!value) {
      return Promise.reject(type ? '请填写返回值失败示例' : '请填写返回值成功示例');
    } else if (!isJson(value)) {
      return Promise.reject('格式错误');
    } else {
      return Promise.resolve();
    }
  };

  const getFormItems = () => {
    const { returningType = 0, successExample, failedExample } = value;
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return [
      {
        label: {
          label: '返回类型',
          ...layout,
        },
        name: 'returningType',
        options: {
          initialValue: returningType,
          rules: [{ required: true, message: '请选择返回类型' }],
        },
        component: (
          <Select placeholder='请选择返回类型'>
            {['json'].map((item, index) => (
              <Select.Option value={index} key={item}>
                {item}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      {
        label: {
          label: '返回值成功示例',
          ...layout,
        },
        name: 'successExample',
        options: {
          initialValue: successExample,
          rules: [
            {
              required: true,
              validator: (rule, value) => validateReturnValue(rule, value, 0),
            },
          ],
        },
        component: <Input.TextArea placeholder={josnExample} rows={8} />,
        after: (
          <Button type='link' onClick={() => handleFormatter(0)}>
            格式化
          </Button>
        ),
      },
      {
        label: {
          label: '返回值失败示例',
          ...layout,
        },
        name: 'failedExample',
        options: {
          initialValue: failedExample,
          rules: [
            {
              required: true,
              validator: (rule, value) => validateReturnValue(rule, value, 1),
            },
          ],
        },
        component: <Input.TextArea placeholder={josnExample} rows={8} />,
        after: (
          <Button type='link' onClick={() => handleFormatter(1)}>
            格式化
          </Button>
        ),
      },
    ];
  };

  return (
    <div>
      {getFormItems().map((item, index) => (
        <FormItem key={index} form={form} item={item} colNum={1} />
      ))}
    </div>
  );
};
export default ReturnResult;
